package com.aliang.clickhouseautoconfig.config;

import com.aliang.clickhouseautoconfig.core.ClickhouseClient;
import com.aliang.clickhouseautoconfig.properties.ClickhouseProperties;
import com.aliang.clickhouseautoconfig.pool.ClickhousePool;
import com.aliang.clickhouseautoconfig.pool.ClickhousePoolImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration //todo 自动配置类
@ConditionalOnClass({ClickhouseProperties.class}) // 当 classpath下存在条件中的class时,实例化当前bean
@EnableConfigurationProperties({ClickhouseProperties.class}) // 表示此类如果有ConfigurationProperties注解,则会注入给spring容器管理。否则配置类不会自动注入
public class ClickhouseAutoConfiguration {

    @Autowired
    private ClickhouseProperties clickhouseProperties;

    //todo 配置类
    @Bean
    @ConditionalOnMissingBean(ClickhousePool.class)
    public ClickhousePool clickhousePool(){
        final ClickhousePoolImpl clickhousePool = new ClickhousePoolImpl();
        clickhousePool.setName(clickhouseProperties.getName());
        clickhousePool.setPassword(clickhouseProperties.getPassword());
        clickhousePool.setUrl(clickhouseProperties.getUrl());
        clickhousePool.setDriverClass(clickhouseProperties.getDriverClass());
        clickhousePool.setCoreSize(clickhouseProperties.getCoreSize());
        clickhousePool.setMaxSize(clickhouseProperties.getMaxSize());
        //此方法很重要必须要调用，才会初始化连接池
        clickhousePool.init();
        return clickhousePool;
    }

    @Bean
    public ClickhouseClient clickhouseClient(){
        ClickhouseClient clickhouseClient = new ClickhouseClient();
        clickhouseClient.setClickhousePool(clickhousePool());
        return clickhouseClient;
    }
}
